package com.woniuxy.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.woniuxy.entity.Role;
import com.woniuxy.service.RoleService;
import com.woniuxy.utils.Result;

@RestController
@RequestMapping("/role")
public class RoleController {
	@Autowired
	private RoleService roleService;
	
	
	//查询所有角色
	@GetMapping("/all")
	public List<Role> findAllRole(){
		
		List<Role> roles = roleService.findAllRole();
		
		for (Role role : roles) {
			ArrayList<String> pnames = new ArrayList<String>();
			int rid = role.getRid();
			List<Integer> pids = findPidByRid(rid);
			for (int pid : pids) {
				String pname = findPameByPid(pid);
				pnames.add(pname);
			}
			role.setPermission(pnames);
		}
//		for (Role role : roles) {
//			System.out.println("------------"+role.getRname()+"的权限有："+role.getPermission()+"-------------");
//		}
		return roles;
		}
	//通过角色id查询权限id
	@GetMapping("/findpidbyrid")
	public List<Integer> findPidByRid(int rid){
		return roleService.findPidByRid(rid);
	}
	//通过权限id查询权限名称
	@GetMapping("/findpnamebypid")
	public String findPameByPid(int pid){
		return roleService.findPnameByPid(pid);
	}
	//根据关键字模糊查询角色
	@GetMapping("/findrolebywords")
	public Result<Object> findRoleByWords(String words){
		Result<Object> result = new Result<>();
		List<Role> roles = roleService.findRoleByWords(words);
		if(roles==null) {
			result.setMessage("没有数据");
			return result;
		}
		result.setData(roles);
		return result;
	}
	//根据状态查询角色
	@GetMapping("/findrolebystatus")
	public Result<Object> findRoleByStatus(int status){
		Result<Object> result = new Result<>();
		if (status==1 || status==0) {
			List<Role> roles = roleService.findRoleByStatus(status);
			if(roles==null) {
				result.setMessage("没有数据");
				return result;
			}
			result.setData(roles);
			return result;
		}
		result.setMessage("异常");
		return result;
	}
	//新增角色--------------------存疑
	@GetMapping("/insert")
	public int insertRole() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String ctime = sdf.format(date);
		Role role = new Role().setRname("小张童鞋").setRcode("zhang").setStatus(1).setDescription("划水").setCtime(ctime);
		roleService.insertRole(role);
		return 0;
	}
	//删除角色
	@GetMapping("/delbyrid")
	public Result<Object> delByRid(int rid) {
		roleService.delByRid(rid);
		List<Role> roles = roleService.findAllRole();
		Result<Object> result = new Result<>();
		result.setData(roles);
		result.setMessage("删除角色成功");
		return result;
	}
	
	
}
